<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/myblogs/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/myblogs/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/myblogs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/myblogs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/myblogs/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/myblogs/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/myblogs/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/myblogs/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/myblogs/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="REST,前端，后端," />





  <link rel="alternate" href="/myblogs/atom.xml" title="天行健の博客" type="application/atom+xml" />






<meta name="description" content="既然MVC模式这么好，难道它就没有不足的地方吗？我认为MVC至少有以下三点不足：(1)每次请求必须经过“控制器-&gt;模型-&gt;视图”这个流程，用户才能看到最终的展现的界面，这个过程似乎有些复杂；(2)实际上视图是依赖于模型的，换句话说，如果没有模型，视图也无法呈现出最终的效果；(3)渲染视图的过程是在服务端来完成的，最终呈现给浏览器的是带有模型的视图页面，性能无法得到很好的优化。 为了使数">
<meta property="og:type" content="article">
<meta property="og:title" content="REST风格框架实战（从MVC到前后端分离）">
<meta property="og:url" content="https://joy_24.gitee.io/2020/11/25/rest1/index.html">
<meta property="og:site_name" content="天行健の博客">
<meta property="og:description" content="既然MVC模式这么好，难道它就没有不足的地方吗？我认为MVC至少有以下三点不足：(1)每次请求必须经过“控制器-&gt;模型-&gt;视图”这个流程，用户才能看到最终的展现的界面，这个过程似乎有些复杂；(2)实际上视图是依赖于模型的，换句话说，如果没有模型，视图也无法呈现出最终的效果；(3)渲染视图的过程是在服务端来完成的，最终呈现给浏览器的是带有模型的视图页面，性能无法得到很好的优化。 为了使数">
<meta property="og:locale">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/25/rest1/0.jpg">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/25/rest1/1.1.jpg">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/25/rest1/1.2.1.jpg">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/25/rest1/1.2.2.jpg">
<meta property="og:image" content="https://joy_24.gitee.io/myblogs/2020/11/25/rest1/2.jpg">
<meta property="article:published_time" content="2020-11-25T07:44:32.000Z">
<meta property="article:modified_time" content="2021-10-26T07:03:12.745Z">
<meta property="article:author" content="Joy Wang">
<meta property="article:tag" content="REST,前端，后端">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://joy_24.gitee.io/myblogs/2020/11/25/rest1/0.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://joy_24.gitee.io/2020/11/25/rest1/"/>





  <title>REST风格框架实战（从MVC到前后端分离） | 天行健の博客</title>
  








<meta name="generator" content="Hexo 5.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a target="_blank" rel="noopener" href="https://github.com/JoyWJ" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>


    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/myblogs/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">天行健の博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一个开发博客的初学者。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/myblogs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/myblogs/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/myblogs/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/myblogs/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/myblogs/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/myblogs/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://joy_24.gitee.io/myblogs/2020/11/25/rest1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/myblogs/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="天行健の博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">REST风格框架实战（从MVC到前后端分离）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-11-25T15:44:32+08:00">
                2020-11-25
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/myblogs/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/" itemprop="url" rel="index">
                    <span itemprop="name">中间件</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  8.3k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  34
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>既然MVC模式这么好，难道它就没有不足的地方吗？我认为MVC至少有以下三点不足：<br>(1)每次请求必须经过“控制器-&gt;模型-&gt;视图”这个流程，用户才能看到最终的展现的界面，这个过程似乎有些复杂；<br>(2)实际上视图是依赖于模型的，换句话说，如果没有模型，视图也无法呈现出最终的效果；<br>(3)渲染视图的过程是在服务端来完成的，最终呈现给浏览器的是带有模型的视图页面，<strong>性能无法得到很好的优化</strong>。</p>
<p>为了使数据展现过程更加直接，并且提供更好的用户体验，我们有必要对MVC模式进行改进。不妨这样来尝试：<br>首先从浏览器发送AJAX请求，然后服务端接受该请求并返回JSON数据返回给浏览器，最后在浏览器中进行界面渲染。改进后的MVC模式如下图所示：</p>
<p><img src="/myblogs/2020/11/25/rest1/0.jpg"></p>
<p>前后端分离的好处：</p>
<p>后端的复用<br>前后端更加自由的独立作业<br>分工造成专业<br>按照标准交付（后端可以做兼职了）</p>
<p>新事物的产生：</p>
<p>前端高速发展<br>JS框架<br>CSS脚本化<br>前端编译技术<br>Single-page Application<br>接口相关技术<br>类似 Swagger 一样的接口标准<br>REST具有更高的可行性<br>数据传输标准 JSend, JSON API<br>HTTP2 对请求的合并<br>后端细化<br>为接口而生的 PHP 框架<br>路由层的显现</p>
<p>没有前后端分离时的开发模式：</p>
<p>后端是跟数据库跟服务器打交道的，前端是跟浏览器打交道的。似乎没有什么问题，大家都这么认为的。当然这没有什么错，我们一直以来都认为仅仅是以浏览器作分界，把这两部分的代码分离出来。但是前后端分离的初衷是为了分离前后端开发人员的职责，同时解决开发模式的问题。但似乎他们的职责在以前甚至于现在都并不明确，虽然前端是跟浏览器打交道，但是最终浏览器拿到的页面是服务器通过模板生成的一个临时静态页面而已。所以，实际上后端也掺和进来了，因为他要处理模板。</p>
<p>当然，一般传统上的开发协作模式有两种：</p>
<p>一种是前端先写一个静态页面，写好后，让后端去套模板。静态页面可以本地开发，也无需考虑业务逻辑只需要实现View即可。不足是还需要后端套模板，这些前端代码后端需要浏览一遍，以免出错。</p>
<p>另一种协作模式是，前端直接去写模板，这样做的问题在于，前端编写过程中很依赖与后端环境，如果当后端没写完的情况下，前端几乎没法干活。</p>
<p>显然这两种方式似乎都有很多问题，但至少这还是目前为止大部分公司所采用的模式。他们从物理层来区分前后端的开发，同时淡化了前端在逻辑上的色彩。<br>由于前端所做的事情就是来实现一个页面的静态版本，所以，大多数公司又给前端工程师们找了点活干。你去看现在公司在招聘的时候前端工程师的要求，除了对页面的基本制作技能外还有额外的设计职责。</p>
<h2 id="一-MVC-概述"><a href="#一-MVC-概述" class="headerlink" title="一. MVC 概述"></a>一. MVC 概述</h2><p><strong>1. 理解 MVC</strong></p>
<p>　　MVC是一种经典的设计模式，全名为Model-View-Controller，即模型-视图-控制器。其中，模型是用于封装数据的载体，例如，在Java中一般通过一个简单的POJO（Plain Ordinary Java Object）来表示，其本质是一个普通的java Bean，包含一系列的成员变量及其getter/setter方法。对于视图而言，它更加偏重于展现，也就是说，视图决定了界面到底长什么样子，在Java中可通过JSP来充当视图，或者通过纯HTML的方式进行展现，而后者才是目前的主流。模型和视图需要通过控制器来进行粘合，例如，用户发送一个HTTP请求，此时该请求首先会进入控制器，然后控制器去获取数据并将其封装为模型，最后将模型传递到视图中进行展现。综上所述，MVC的交互过程如下图所示。</p>
<p><img src="/myblogs/2020/11/25/rest1/1.1.jpg"></p>
<p><strong>2. MVC 模式的优点与不足</strong></p>
<h5 id="MVC模式早在上个世纪70年代就诞生了，直到今天它依然存在，可见生命力相当之强。MVC模式最早应用于Smalltalk语言中，最后在其它许多开发语言中都得到了很好的应用。随着包括Struts、Spring-MVC在内的MVC框架的出现，MVC模式真正落地，并使得开发更加高效、代码耦合度尽量减小、应用程序各部分的职责更加清晰。"><a href="#MVC模式早在上个世纪70年代就诞生了，直到今天它依然存在，可见生命力相当之强。MVC模式最早应用于Smalltalk语言中，最后在其它许多开发语言中都得到了很好的应用。随着包括Struts、Spring-MVC在内的MVC框架的出现，MVC模式真正落地，并使得开发更加高效、代码耦合度尽量减小、应用程序各部分的职责更加清晰。" class="headerlink" title="　　MVC模式早在上个世纪70年代就诞生了，直到今天它依然存在，可见生命力相当之强。MVC模式最早应用于Smalltalk语言中，最后在其它许多开发语言中都得到了很好的应用。随着包括Struts、Spring MVC在内的MVC框架的出现，MVC模式真正落地，并使得开发更加高效、代码耦合度尽量减小、应用程序各部分的职责更加清晰。"></a>　　MVC模式早在上个世纪70年代就诞生了，直到今天它依然存在，可见生命力相当之强。MVC模式最早应用于Smalltalk语言中，最后在其它许多开发语言中都得到了很好的应用。随着包括Struts、Spring MVC在内的MVC框架的出现，MVC模式真正落地，并使得开发更加高效、代码耦合度尽量减小、应用程序各部分的职责更加清晰。</h5><p>　　既然MVC模式这么好，难道它就没有不足的地方吗？我认为MVC至少有以下三点不足：</p>
<ul>
<li><p>每次请求必须经过“控制器-&gt;模型-&gt;视图”这个流程，用户才能看到最终的展现的界面，这个过程似乎有些复杂；</p>
</li>
<li><p>实际上视图是依赖于模型的，换句话说，如果没有模型，视图也无法呈现出最终的效果；</p>
</li>
<li><p>渲染视图的过程是在服务端来完成的，最终呈现给浏览器的是带有模型的视图页面，性能无法得到很好的优化。</p>
<p>　　为了使数据展现过程更加直接，并且提供更好的用户体验，我们有必要对MVC模式进行改进。不妨这样来尝试：<strong>首先从浏览器发送AJAX请求，然后服务端接受该请求并返回JSON数据返回给浏览器，最后在浏览器中进行界面渲染。</strong>改进后的MVC模式如下图所示：</p>
</li>
</ul>
<p><img src="/myblogs/2020/11/25/rest1/1.2.1.jpg"></p>
<p>也就是说，我们输入的是AJAX请求，输出的是JSON数据，市面上有这样的技术来实现这个功能吗？答案是REST。</p>
<p>　　REST全称是Representational State Transfer（表述性状态转移），它是Roy Fielding博士在2000年写的一篇关于软件架构风格的论文，此文一出，威震四方！国内外许多知名互联网公司纷纷开始采用这种轻量级的Web服务，大家习惯将其称为RESTful Web Services，或简称REST服务。]</p>
<p>　　如果将浏览器这一端视为前端，而服务器那一端视为后端的话，可以将以上改进后的MVC模式简化为以下前后端分离模式，如下图所示：</p>
<p><img src="/myblogs/2020/11/25/rest1/1.2.2.jpg"></p>
<p>可见，<strong>采用REST分格的架构可以使得前端关注界面展现，后端关注业务逻辑，分工明确，职责清晰。</strong>那么，如何使用REST架构将应用程序进行前后端分离呢？我们接下来继续探讨，首先我们需要认识REST。</p>
<h2 id="二-认识-REST"><a href="#二-认识-REST" class="headerlink" title="二. 认识 REST"></a>二. 认识 REST</h2><p>　　REST本质上是使用URL来访问资源的一种方式。众所周知，URL(Uniform Resoure Locator:统一资源定位器)就是我们平常使用的请求地址了，其中包括两部分：请求方式与请求路径，比较常见的请求方式是GET与POST，但在REST中又提出了几种其它类型的请求方式，汇总起来有六种：GET、POST、PUT、DELETE、HEAD、OPTIONS。尤其是前四种，正好与CRUD（Create-Retrieve-Update-Delete，增删改查）四种操作相对应，例如，GET（查）、POST（增）、PUT（改）、DELETE（删），这正是REST与CRUD的异曲同工之妙！<strong>需要强调的是，REST是面向资源(ROA)的，这里提到的资源，实际上就是我们常说的领域对象，在系统设计过程中，我们经常通过领域对象来进行数据建模。</strong></p>
<p>　　REST是一个无状态的架构模式，因为在任何时候都可以由客户端发出请求到服务端，最终返回自己想要的数据，当前请求不会受到上次请求的影响。也就是说，<strong>服务端将内部资源发布REST服务，客户端通过URL来定位这些资源并通过HTTP协议来访问它们。</strong>下面我们举几个例子对REST请求进行简单描述：</p>
<p><img src="/myblogs/2020/11/25/rest1/2.jpg"></p>
<p>可见，请求路径相同但请求方式不同，所代表的业务操作也不同，例如，/advertiser/1这个请求，带有GET、PUT、DELETE三种不同的请求方式，对应三种不同的业务操作。</p>
<p>　　虽然REST看起来还是很简单的，实际上我们往往需要提供一个REST框架，让其实现前后端分离架构，让开发人员将精力集中在业务上，而并非那些具体的技术细节。下面我们将使用Java技术来实现这个REST框架，整体框架会基于Spring进行开发。</p>
<h2 id="三-实现REST框架"><a href="#三-实现REST框架" class="headerlink" title="三. 实现REST框架"></a>三. 实现REST框架</h2><p><strong>1、统一响应结构</strong></p>
<p>　　使用REST框架实现前后端分离架构，我们需要首先确定返回的JSON响应结构是统一的，也就是说，每个REST请求将返回相同结构的JSON响应结构。不妨定义一个相对通用的JSON响应结构，其中包含两部分：元数据与返回值，其中，元数据表示操作是否成功与返回值消息等，返回值对应服务端方法所返回的数据。该JSON响应结构如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">        &quot;meta&quot;: &#123;</span><br><span class="line">            &quot;success&quot;: true,</span><br><span class="line">            &quot;message&quot;: &quot;ok&quot;</span><br><span class="line">        &#125;,</span><br><span class="line">        &quot;data&quot;: ...</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>为了在框架中映射以上JSON响应结构，我们需要编写一个Response类与其对应：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;**</span><br><span class="line"> * Title: 统一响应结构 </span><br><span class="line"> * Description:使用REST框架实现前后端分离架构，我们需要首先确定返回的JSON响应结构是统一的，</span><br><span class="line"> * 也就是说，每个REST请求将返回相同结构的JSON响应结构。不妨定义一个相对通用的JSON响应结构，其</span><br><span class="line"> * 中包含两部分：元数据与返回值，其中，元数据表示操作是否成功与返回值消息等，返回值对应服务端方法所返回的数据。</span><br><span class="line"> * &#123; &quot;meta&quot;: &#123; &quot;success&quot;: true, &quot;message&quot;: &quot;ok&quot; &#125;, &quot;data&quot;: ... &#125;</span><br><span class="line"> * </span><br><span class="line"> * @author rico</span><br><span class="line"> * @created 2017年7月4日 下午5:06:00</span><br><span class="line"> *&#x2F;</span><br><span class="line">public class Response &#123;</span><br><span class="line"></span><br><span class="line">    private static final String OK &#x3D; &quot;ok&quot;;</span><br><span class="line">    private static final String ERROR &#x3D; &quot;error&quot;;</span><br><span class="line"></span><br><span class="line">    private Meta meta;     &#x2F;&#x2F; 元数据</span><br><span class="line">    private Object data;   &#x2F;&#x2F; 响应内容</span><br><span class="line"></span><br><span class="line">    public Response success() &#123;</span><br><span class="line">        this.meta &#x3D; new Meta(true, OK);</span><br><span class="line">        return this;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public Response success(Object data) &#123;</span><br><span class="line">        this.meta &#x3D; new Meta(true, OK);</span><br><span class="line">        this.data &#x3D; data;</span><br><span class="line">        return this;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public Response failure() &#123;</span><br><span class="line">        this.meta &#x3D; new Meta(false, ERROR);</span><br><span class="line">        return this;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public Response failure(String message) &#123;</span><br><span class="line">        this.meta &#x3D; new Meta(false, message);</span><br><span class="line">        return this;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public Meta getMeta() &#123;</span><br><span class="line">        return meta;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public Object getData() &#123;</span><br><span class="line">        return data;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    &#x2F;**</span><br><span class="line">     * Title: 请求元数据</span><br><span class="line">     * @author rico</span><br><span class="line">     * @created 2017年7月4日 下午5:08:12</span><br><span class="line">     *&#x2F;</span><br><span class="line">    public class Meta &#123;</span><br><span class="line"></span><br><span class="line">        private boolean success;</span><br><span class="line">        private String message;</span><br><span class="line"></span><br><span class="line">        public Meta(boolean success) &#123;</span><br><span class="line">            this.success &#x3D; success;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        public Meta(boolean success, String message) &#123;</span><br><span class="line">            this.success &#x3D; success;</span><br><span class="line">            this.message &#x3D; message;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        public boolean isSuccess() &#123;</span><br><span class="line">            return success;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        public String getMessage() &#123;</span><br><span class="line">            return message;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>以上Response类包括两类通用返回值消息：ok 与 error，还包括两个常用的操作方法：success( )与failure( )，通过一个内部类来展现元数据结构，我们在下文中多次会使用该Response类。</p>
<p>实现该REST框架需要考虑许多问题，首当其冲的就是前后数据流转问题，即HTTP消息与Java对象之间的转化问题。</p>
<p><strong>2、前后台数据流转</strong><br>　　<br>　　前后台数据流转问题具体指的是什么？不妨通过一些例子进行说明。比如，通过浏览器发送了一个普通的HTTP请求，该请求携带了一个JSON格式的参数，在服务端需要将该JSON参数转换为普通的Java对象；再比如，在服务端获取了数据，此时该数据是一个普通的Java对象，然后需要将这个Java对象转换为JSON字符串，并将其返回到浏览器中进行渲染，这个过程就涉及HTTP消息与Java对象之间的转化问题。</p>
<p>　　实际上，Spring MVC已经为我们提供了这类转化特性，只需在Controller的方法参数中使用@RequestBody注解定义需要转化的参数即可；<br>类似地，若需要对Controller的方法返回值进行转化，则需要在该返回值上使用@ResponseBody注解来定义，如以下代码片段：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">@RequestMapping(&quot;&#x2F;users&quot;)</span><br><span class="line">public class UserController &#123;</span><br><span class="line"></span><br><span class="line">    private UserService userService;</span><br><span class="line"></span><br><span class="line">    &#x2F;** Log4j日志处理(@author: rico) *&#x2F;</span><br><span class="line">    private static final Logger log &#x3D; Logger.getLogger(UserController.class);</span><br><span class="line"></span><br><span class="line">    public UserService getUserService() &#123;</span><br><span class="line">        return userService;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Resource(name &#x3D; &quot;userService&quot;)</span><br><span class="line">    public void setUserService(UserService userService) &#123;</span><br><span class="line">        this.userService &#x3D; userService;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @RequestMapping(value &#x3D; &quot;&#x2F;user&quot;, method &#x3D; RequestMethod.PUT, produces &#x3D; &quot;application&#x2F;json&quot;, </span><br><span class="line">            consumes &#x3D; &quot;application&#x2F;json&quot;)</span><br><span class="line">    @ResponseBody     &#x2F;&#x2F; 将 Java 对象转化为特定的HTTP消息</span><br><span class="line">    public User addUser(@RequestBody User user) &#123;  &#x2F;&#x2F; 将接收到的HTTP消息转化为Java对象</span><br><span class="line">        userService.addUser(user);</span><br><span class="line">        log.debug(&quot;添加用户 :&quot; + user);</span><br><span class="line">        return user;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>当然，@ResponseBody注解也可以定义在类上，这样所有的方法都继承了该特性。由于经常会使用到@ResponseBody注解，所以Spring提供了一个名为@RestController的注解来取代以上的@Controller注解，这样我们就可以省略返回值前面的@ResponseBody注解了，但参数前面的@RequestBody注解是无法省略的。实际上，看看Spring中对应@RestController注解的源码便可知晓：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">@Target(&#123;ElementType.TYPE&#125;)  </span><br><span class="line">@Retention(RetentionPolicy.RUNTIME)  </span><br><span class="line">@Documented  </span><br><span class="line">@Controller  </span><br><span class="line">@ResponseBody  </span><br><span class="line">public @interface RestController &#123;  </span><br><span class="line"></span><br><span class="line">    String value() default &quot;&quot;;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可见，@RestController注解已经被@Controller与@ResponseBody注解定义过了，Spring框架会识别这类注解。需要注意的是，该特性在Spring 4.0中才引入。<br>因此，我们可将以上代码进行如下改写：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">@RestController</span><br><span class="line">@RequestMapping(&quot;&#x2F;users&quot;)</span><br><span class="line">public class UserController &#123;</span><br><span class="line"></span><br><span class="line">    private UserService userService;</span><br><span class="line"></span><br><span class="line">    &#x2F;** Log4j日志处理(@author: rico) *&#x2F;</span><br><span class="line">    private static final Logger log &#x3D; Logger.getLogger(UserController.class);</span><br><span class="line"></span><br><span class="line">    public UserService getUserService() &#123;</span><br><span class="line">        return userService;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Resource(name &#x3D; &quot;userService&quot;)</span><br><span class="line">    public void setUserService(UserService userService) &#123;</span><br><span class="line">        this.userService &#x3D; userService;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @RequestMapping(value &#x3D; &quot;&#x2F;user&quot;, method &#x3D; RequestMethod.PUT, produces &#x3D; &quot;application&#x2F;json&quot;, </span><br><span class="line">            consumes &#x3D; &quot;application&#x2F;json&quot;)</span><br><span class="line">    public User addUser(@RequestBody User user) &#123;  &#x2F;&#x2F; 将接收到的HTTP消息转化为Java对象</span><br><span class="line">        userService.addUser(user);</span><br><span class="line">        log.debug(&quot;添加用户 :&quot; + user);</span><br><span class="line">        return user;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>除了使用注解来定义消息转化行为以外，我们还需要添加Jackson包进行支持，Maven依赖如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- JSON: jackson --&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.codehaus.jackson&lt;&#x2F;groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;jackson-core-asl&lt;&#x2F;artifactId&gt;</span><br><span class="line">    &lt;version&gt;1.9.12&lt;&#x2F;version&gt;</span><br><span class="line">&lt;&#x2F;dependency&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.codehaus.jackson&lt;&#x2F;groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;jackson-mapper-lgpl&lt;&#x2F;artifactId&gt;</span><br><span class="line">    &lt;version&gt;1.9.12&lt;&#x2F;version&gt;</span><br><span class="line">&lt;&#x2F;dependency&gt;</span><br></pre></td></tr></table></figure>

<p>在Spring配置文件中添加以下配置即可：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- 该配置会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter两个Bean，</span><br><span class="line">    这是SpringMVC为@Controllers分发请求所必需的，并提供了数据绑定支持、@NumberFormatannotation支持、</span><br><span class="line">    @DateTimeFormat支持、@Valid支持、读写XML的支持和读写JSON的支持等功能。 --&gt;</span><br><span class="line">    &lt;mvc:annotation-driven &#x2F;&gt;</span><br></pre></td></tr></table></figure>

<p>通过以上过程，我们已经完成了一个基于SpringMVC的REST框架，只不过该框架还非常单薄，还缺乏很多关键性特性，尤其是异常处理。</p>
<p><strong>3、处理异常行为</strong></p>
<p>　　在Spring MVC中，我们可以使用AOP技术，编写一个全局的异常处理切面类，用它来统一处理所有的异常行为，在Spring 3.2中才开始提供。使用很简单，只需定义一个类，并通过@ControllerAdvice注解将其标注即可，同时需要使用@ResponseBody注解表示返回值可序列化为JSON字符串。<br>代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;**        </span><br><span class="line"> * Title: 全局异常处理切面    </span><br><span class="line"> * Description: 利用 @ControllerAdvice + @ExceptionHandler 组合处理Controller层RuntimeException异常</span><br><span class="line"> * @author rico       </span><br><span class="line"> * @created 2017年7月4日 下午4:29:07    </span><br><span class="line"> *&#x2F;      </span><br><span class="line">@ControllerAdvice   &#x2F;&#x2F; 控制器增强</span><br><span class="line">@ResponseBody</span><br><span class="line">public class ExceptionAspect &#123;</span><br><span class="line"></span><br><span class="line">    &#x2F;** Log4j日志处理(@author: rico) *&#x2F;</span><br><span class="line">    private static final Logger log &#x3D; Logger.getLogger(ExceptionAspect.class);</span><br><span class="line"></span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 400 - Bad Request</span><br><span class="line">     *&#x2F;</span><br><span class="line">    @ResponseStatus(HttpStatus.BAD_REQUEST)</span><br><span class="line">    @ExceptionHandler(HttpMessageNotReadableException.class)</span><br><span class="line">    public Response handleHttpMessageNotReadableException(</span><br><span class="line">            HttpMessageNotReadableException e) &#123;</span><br><span class="line">        log.error(&quot;could_not_read_json...&quot;, e);</span><br><span class="line">        return new Response().failure(&quot;could_not_read_json&quot;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 400 - Bad Request</span><br><span class="line">     *&#x2F;</span><br><span class="line">    @ResponseStatus(HttpStatus.BAD_REQUEST)</span><br><span class="line">    @ExceptionHandler(&#123;MethodArgumentNotValidException.class&#125;)</span><br><span class="line">    public Response handleValidationException(MethodArgumentNotValidException e) &#123;</span><br><span class="line">        log.error(&quot;parameter_validation_exception...&quot;, e);</span><br><span class="line">        return new Response().failure(&quot;parameter_validation_exception&quot;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 405 - Method Not Allowed。HttpRequestMethodNotSupportedException</span><br><span class="line">     * 是ServletException的子类,需要Servlet API支持</span><br><span class="line">     *&#x2F;</span><br><span class="line">    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)</span><br><span class="line">    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)</span><br><span class="line">    public Response handleHttpRequestMethodNotSupportedException(</span><br><span class="line">            HttpRequestMethodNotSupportedException e) &#123;</span><br><span class="line">        log.error(&quot;request_method_not_supported...&quot;, e);</span><br><span class="line">        return new Response().failure(&quot;request_method_not_supported&quot;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 415 - Unsupported Media Type。HttpMediaTypeNotSupportedException</span><br><span class="line">     * 是ServletException的子类,需要Servlet API支持</span><br><span class="line">     *&#x2F;</span><br><span class="line">    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)</span><br><span class="line">    @ExceptionHandler(&#123; HttpMediaTypeNotSupportedException.class &#125;)</span><br><span class="line">    public Response handleHttpMediaTypeNotSupportedException(Exception e) &#123;</span><br><span class="line">        log.error(&quot;content_type_not_supported...&quot;, e);</span><br><span class="line">        return new Response().failure(&quot;content_type_not_supported&quot;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 500 - Internal Server Error</span><br><span class="line">     *&#x2F;</span><br><span class="line">    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)</span><br><span class="line">    @ExceptionHandler(TokenException.class)</span><br><span class="line">    public Response handleTokenException(Exception e) &#123;</span><br><span class="line">        log.error(&quot;Token is invaild...&quot;, e);</span><br><span class="line">        return new Response().failure(&quot;Token is invaild&quot;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    &#x2F;**</span><br><span class="line">     * 500 - Internal Server Error</span><br><span class="line">     *&#x2F;</span><br><span class="line">    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)</span><br><span class="line">    @ExceptionHandler(Exception.class)</span><br><span class="line">    public Response handleException(Exception e) &#123;</span><br><span class="line">        log.error(&quot;Internal Server Error...&quot;, e);</span><br><span class="line">        return new Response().failure(&quot;Internal Server Error&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可见，在ExceptionAdvice类中包含一系列的异常处理方法，每个方法都通过@ResponseStatus注解定义了响应状态码，此外还通过@ExceptionHandler注解指定了具体需要拦截的异常类。以上过程只是包含了一部分的异常情况，若需处理其它异常，可添加方法具体的方法。需要注意的是，在运行时从上往下依次调用每个异常处理方法，匹配当前异常类型是否与@ExceptionHandler注解所定义的异常相匹配，若匹配，则执行该方法，同时忽略后续所有的异常处理方法，最终会返回经JSON序列化后的Response对象。</p>
<p><strong>4、支持参数验证</strong></p>
<p>　　我们回到上文所提到的示例，这里处理一个普通的PUT请求，代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">@RestController</span><br><span class="line">@RequestMapping(&quot;&#x2F;users&quot;)</span><br><span class="line">public class UserController &#123;</span><br><span class="line"></span><br><span class="line">    private UserService userService;</span><br><span class="line"></span><br><span class="line">    &#x2F;** Log4j日志处理(@author: rico) *&#x2F;</span><br><span class="line">    private static final Logger log &#x3D; Logger.getLogger(UserController.class);</span><br><span class="line"></span><br><span class="line">    public UserService getUserService() &#123;</span><br><span class="line">        return userService;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Resource(name &#x3D; &quot;userService&quot;)</span><br><span class="line">    public void setUserService(UserService userService) &#123;</span><br><span class="line">        this.userService &#x3D; userService;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @RequestMapping(value &#x3D; &quot;&#x2F;user&quot;, method &#x3D; RequestMethod.PUT, produces &#x3D; &quot;application&#x2F;json&quot;, </span><br><span class="line">            consumes &#x3D; &quot;application&#x2F;json&quot;)</span><br><span class="line">    public User addUser(@RequestBody User user) &#123;  &#x2F;&#x2F; 将接收到的HTTP消息转化为Java对象</span><br><span class="line">        userService.addUser(user);</span><br><span class="line">        log.debug(&quot;添加用户 :&quot; + user);</span><br><span class="line">        return user;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其中，User参数包含若干属性，通过以下类结构可见，它是一个传统的POJO：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">public class User implements Serializable&#123;</span><br><span class="line"></span><br><span class="line">    private static final long serialVersionUID &#x3D; 1L;</span><br><span class="line"></span><br><span class="line">    private int id;</span><br><span class="line">    private String uname;</span><br><span class="line">    private String passwd;</span><br><span class="line">    private String gentle;</span><br><span class="line">    private String email;</span><br><span class="line">    private String city;</span><br><span class="line"></span><br><span class="line">    public User() &#123;</span><br><span class="line">        super();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    &#x2F;&#x2F; getter&#x2F;setter</span><br><span class="line"></span><br><span class="line">    &#x2F;&#x2F; toString</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果业务上需要确保User对象的uname属性必填，如何实现呢？若将这类参数验证的代码写死在Controller中，势必会与正常的业务逻辑搅在一起，导致责任不够单一，违背于“单一责任原则”。建议将其参数验证行为从Controller中剥离出来，放到另外的类中，这里仅通过@Valid注解来定义uname参数，并通过Bean Validation的参考实现Hibernate Validator的@NotEmpty注解来定义User类中的uname属性，就像下面这样：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">@RestController</span><br><span class="line">@RequestMapping(&quot;&#x2F;users&quot;)</span><br><span class="line">public class UserController &#123;</span><br><span class="line"></span><br><span class="line">    private UserService userService;</span><br><span class="line"></span><br><span class="line">    &#x2F;** Log4j日志处理(@author: rico) *&#x2F;</span><br><span class="line">    private static final Logger log &#x3D; Logger.getLogger(UserController.class);</span><br><span class="line"></span><br><span class="line">    public UserService getUserService() &#123;</span><br><span class="line">        return userService;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Resource(name &#x3D; &quot;userService&quot;)</span><br><span class="line">    public void setUserService(UserService userService) &#123;</span><br><span class="line">        this.userService &#x3D; userService;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @RequestMapping(value &#x3D; &quot;&#x2F;user&quot;, method &#x3D; RequestMethod.PUT, produces &#x3D; &quot;application&#x2F;json&quot;, </span><br><span class="line">            consumes &#x3D; &quot;application&#x2F;json&quot;)</span><br><span class="line">    public User addUser(@RequestBody  @Valid User user) &#123;  &#x2F;&#x2F; 将接收到的HTTP消息转化为Java对象</span><br><span class="line">        userService.addUser(user);</span><br><span class="line">        log.debug(&quot;添加用户 :&quot; + user);</span><br><span class="line">        return user;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">public class User implements Serializable&#123;</span><br><span class="line"></span><br><span class="line">    private static final long serialVersionUID &#x3D; 1L;</span><br><span class="line"></span><br><span class="line">    private int id;</span><br><span class="line">    @NotEmpty</span><br><span class="line">    private String uname;</span><br><span class="line">    private String passwd;</span><br><span class="line">    private String gentle;</span><br><span class="line">    private String email;</span><br><span class="line">    private String city;</span><br><span class="line"></span><br><span class="line">    public User() &#123;</span><br><span class="line">        super();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    &#x2F;&#x2F; getter&#x2F;setter</span><br><span class="line"></span><br><span class="line">    &#x2F;&#x2F; toString</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里的@Valid注解实际上是Validation Bean规范提供的注解，该规范已由Hibernate Validator框架实现，因此需要添加以下Maven依赖到pom.xml文件中：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;  </span><br><span class="line">    &lt;groupId&gt;org.hibernate&lt;&#x2F;groupId&gt;  </span><br><span class="line">    &lt;artifactId&gt;hibernate-validator&lt;&#x2F;artifactId&gt;  </span><br><span class="line">    &lt;version&gt;$&#123;hibernate-validator.version&#125;&lt;&#x2F;version&gt;  </span><br><span class="line">&lt;&#x2F;dependency&gt;  </span><br></pre></td></tr></table></figure>

<p>需要注意的是，Hibernate Validator与Hibernate没有任何依赖关系，唯一有联系的只是都属于JBoss公司的开源项目而已。然后，我们需要在Spring配置文件中开启该特性，需添加如下配置：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean class&#x3D;&quot;org.springframework.validation.beanvalidation.MethodValidationPostProcessor&quot;&#x2F;&gt; </span><br></pre></td></tr></table></figure>

<p>最后，我们在全局异常处理类中添加对参数验证异常的处理方法，代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">@ControllerAdvice  </span><br><span class="line">@ResponseBody  </span><br><span class="line">public class ExceptionAdvice &#123;  </span><br><span class="line"></span><br><span class="line">    &#x2F;** </span><br><span class="line">     * 400 - Bad Request </span><br><span class="line">     *&#x2F;  </span><br><span class="line">    @ResponseStatus(HttpStatus.BAD_REQUEST)  </span><br><span class="line">    @ExceptionHandler(ValidationException.class)  </span><br><span class="line">    public Response handleValidationException(ValidationException e) &#123;  </span><br><span class="line">        logger.error(&quot;参数验证失败&quot;, e);  </span><br><span class="line">        return new Response().failure(&quot;validation_exception&quot;);  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>至此，REST框架已集成了Bean Validation特性，我们可以使用各种注解来完成所需的参数验证行为了。 </p>
<p>看似该框架可以在本地成功跑起来，整个架构包含两个应用，前端应用提供纯静态的HTML页面，后端应用发布REST API，前端需要通过AJAX调用后端发布的REST API，然而AJAX是不支持跨域访问的，也就是说，前后端两个应用必须在同一个域名下才能访问。这是非常严重的技术障碍，一定需要找到解决方案。</p>
<hr>
<p><strong>5、解决跨域问题</strong></p>
<p>　　比如，前端应用为静态站点且部署在<a target="_blank" rel="noopener" href="http://web.xxx.com/">http://web.xxx.com</a>域下，后端应用发布REST API并部署在<a target="_blank" rel="noopener" href="http://api.xxx.com/">http://api.xxx.com</a>域下，如何使前端应用通过AJAX跨域访问后端应用呢？这需要使用到CORS技术来实现，这也是目前最好的解决方案了。</p>
<p>　　CORS全称为Cross Origin Resource Sharing（跨域资源共享），服务端只需添加相关响应头信息，即可实现客户端发出AJAX跨域请求。</p>
<p>　　CORS技术非常简单，易于实现，目前绝大多数浏览器均已支持该技术（IE8浏览器也支持了），服务端可通过任何编程语言来实现，只要能将CORS响应头写入response对象中即可。</p>
<p>　　下面我们继续扩展REST框架，通过CORS技术实现AJAX跨域访问。首先，我们需要编写一个Filter，用于过滤所有的HTTP请求，并将CORS响应头写入response对象中，代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;**        </span><br><span class="line"> * Title: 跨域访问处理(跨域资源共享)    </span><br><span class="line"> * Description: 解决前后端分离架构中的跨域问题</span><br><span class="line"> * @author rico       </span><br><span class="line"> * @created 2017年7月4日 下午5:00:09    </span><br><span class="line"> *&#x2F;      </span><br><span class="line">public class CorsFilter implements Filter &#123;</span><br><span class="line"></span><br><span class="line">    &#x2F;** Log4j日志处理(@author: rico) *&#x2F;</span><br><span class="line">    private static final Logger log &#x3D; Logger.getLogger(UserController.class);</span><br><span class="line"></span><br><span class="line">    private String allowOrigin;</span><br><span class="line">    private String allowMethods;</span><br><span class="line">    private String allowCredentials;</span><br><span class="line">    private String allowHeaders;</span><br><span class="line">    private String exposeHeaders;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void init(FilterConfig filterConfig) throws ServletException &#123;</span><br><span class="line">        allowOrigin &#x3D; filterConfig.getInitParameter(&quot;allowOrigin&quot;);</span><br><span class="line">        allowMethods &#x3D; filterConfig.getInitParameter(&quot;allowMethods&quot;);</span><br><span class="line">        allowCredentials &#x3D; filterConfig.getInitParameter(&quot;allowCredentials&quot;);</span><br><span class="line">        allowHeaders &#x3D; filterConfig.getInitParameter(&quot;allowHeaders&quot;);</span><br><span class="line">        exposeHeaders &#x3D; filterConfig.getInitParameter(&quot;exposeHeaders&quot;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#x2F;** </span><br><span class="line">     * @description 通过CORS技术实现AJAX跨域访问,只要将CORS响应头写入response对象中即可</span><br><span class="line">     * @author rico       </span><br><span class="line">     * @created 2017年7月4日 下午5:02:38      </span><br><span class="line">     * @param req</span><br><span class="line">     * @param res</span><br><span class="line">     * @param chain</span><br><span class="line">     * @throws IOException</span><br><span class="line">     * @throws ServletException     </span><br><span class="line">     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)     </span><br><span class="line">     *&#x2F;  </span><br><span class="line">    @Override</span><br><span class="line">    public void doFilter(ServletRequest req, ServletResponse res,</span><br><span class="line">            FilterChain chain) throws IOException, ServletException &#123;</span><br><span class="line">        HttpServletRequest request &#x3D; (HttpServletRequest) req;</span><br><span class="line">        HttpServletResponse response &#x3D; (HttpServletResponse) res;</span><br><span class="line">        String currentOrigin &#x3D; request.getHeader(&quot;Origin&quot;);</span><br><span class="line">        log.debug(&quot;currentOrigin : &quot; + currentOrigin);</span><br><span class="line">        if (StringUtil.isNotEmpty(allowOrigin)) &#123;</span><br><span class="line">            List&lt;String&gt; allowOriginList &#x3D; Arrays</span><br><span class="line">                    .asList(allowOrigin.split(&quot;,&quot;));</span><br><span class="line">            log.debug(&quot;allowOriginList : &quot; + allowOrigin);</span><br><span class="line">            if (CollectionUtil.isNotEmpty(allowOriginList)) &#123;</span><br><span class="line">                if (allowOriginList.contains(currentOrigin)) &#123;</span><br><span class="line">                    response.setHeader(&quot;Access-Control-Allow-Origin&quot;,</span><br><span class="line">                            currentOrigin);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        if (StringUtil.isNotEmpty(allowMethods)) &#123;</span><br><span class="line">            response.setHeader(&quot;Access-Control-Allow-Methods&quot;, allowMethods);</span><br><span class="line">        &#125;</span><br><span class="line">        if (StringUtil.isNotEmpty(allowCredentials)) &#123;</span><br><span class="line">            response.setHeader(&quot;Access-Control-Allow-Credentials&quot;,</span><br><span class="line">                    allowCredentials);</span><br><span class="line">        &#125;</span><br><span class="line">        if (StringUtil.isNotEmpty(allowHeaders)) &#123;</span><br><span class="line">            response.setHeader(&quot;Access-Control-Allow-Headers&quot;, allowHeaders);</span><br><span class="line">        &#125;</span><br><span class="line">        if (StringUtil.isNotEmpty(exposeHeaders)) &#123;</span><br><span class="line">            response.setHeader(&quot;Access-Control-Expose-Headers&quot;, exposeHeaders);</span><br><span class="line">        &#125;</span><br><span class="line">        chain.doFilter(req, res);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void destroy() &#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>以上CorsFilter将从web.xml中读取相关Filter初始化参数，并将在处理HTTP请求时将这些参数写入对应的CORS响应头中，下面大致描述一下这些CORS响应头的意义：</p>
<ul>
<li><p>Access-Control-Allow-Origin：允许访问的客户端域名，例如：<a target="_blank" rel="noopener" href="http://web.xxx.com/">http://web.xxx.com</a>，若为*，则表示从任意域都能访问，即不做任何限制；</p>
</li>
<li><p>Access-Control-Allow-Methods：允许访问的方法名，多个方法名用逗号分割，例如：GET,POST,PUT,DELETE,OPTIONS；</p>
</li>
<li><p>Access-Control-Allow-Credentials：是否允许请求带有验证信息，若要获取客户端域下的cookie时，需要将其设置为true；</p>
</li>
<li><p>Access-Control-Allow-Headers：允许服务端访问的客户端请求头，多个请求头用逗号分割，例如：Content-Type；</p>
</li>
<li><p>Access-Control-Expose-Headers：允许客户端访问的服务端响应头，多个响应头用逗号分割。</p>
<p>　需要注意的是，CORS规范中定义Access-Control-Allow-Origin只允许两种取值，要么为*，要么为具体的域名，也就是说，不支持同时配置多个域名。为了解决跨多个域的问题，需要在代码中做一些处理，这里将Filter初始化参数作为一个域名的集合（用逗号分隔），只需从当前请求中获取Origin请求头，就知道是从哪个域中发出的请求，若该请求在以上允许的域名集合中，则将其放入Access-Control-Allow-Origin响应头，这样跨多个域的问题就轻松解决了。以下是web.xml中配置CorsFilter的方法：</p>
</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- 通过CORS技术实现AJAX跨域访问 --&gt;</span><br><span class="line">    &lt;filter&gt;</span><br><span class="line">        &lt;filter-name&gt;corsFilter&lt;&#x2F;filter-name&gt;</span><br><span class="line">        &lt;filter-class&gt;cn.edu.tju.rico.filter.CorsFilter&lt;&#x2F;filter-class&gt;</span><br><span class="line">        &lt;init-param&gt;</span><br><span class="line">            &lt;param-name&gt;allowOrigin&lt;&#x2F;param-name&gt;</span><br><span class="line">            &lt;param-value&gt;http:&#x2F;&#x2F;localhost:8020&lt;&#x2F;param-value&gt;</span><br><span class="line">        &lt;&#x2F;init-param&gt;</span><br><span class="line">        &lt;init-param&gt;</span><br><span class="line">            &lt;param-name&gt;allowMethods&lt;&#x2F;param-name&gt;</span><br><span class="line">            &lt;param-value&gt;GET,POST,PUT,DELETE,OPTIONS&lt;&#x2F;param-value&gt;</span><br><span class="line">        &lt;&#x2F;init-param&gt;</span><br><span class="line">        &lt;init-param&gt;</span><br><span class="line">            &lt;param-name&gt;allowCredentials&lt;&#x2F;param-name&gt;</span><br><span class="line">            &lt;param-value&gt;true&lt;&#x2F;param-value&gt;</span><br><span class="line">        &lt;&#x2F;init-param&gt;</span><br><span class="line">        &lt;init-param&gt;</span><br><span class="line">            &lt;param-name&gt;allowHeaders&lt;&#x2F;param-name&gt;</span><br><span class="line">            &lt;param-value&gt;Content-Type,X-Token&lt;&#x2F;param-value&gt;</span><br><span class="line">        &lt;&#x2F;init-param&gt;</span><br><span class="line">    &lt;&#x2F;filter&gt;</span><br><span class="line">    &lt;filter-mapping&gt;</span><br><span class="line">        &lt;filter-name&gt;corsFilter&lt;&#x2F;filter-name&gt;</span><br><span class="line">        &lt;url-pattern&gt;&#x2F;*&lt;&#x2F;url-pattern&gt;</span><br><span class="line">    &lt;&#x2F;filter-mapping&gt;</span><br></pre></td></tr></table></figure>

<p>完成以上过程即可实现AJAX跨域功能了，但似乎还存在另外一个问题，由于REST是无状态的，后端应用发布的REST API可在用户未登录的情况下被任意调用，这显然是不安全的，如何解决这个问题呢？我们需要为REST请求提供安全机制。</p>
<hr>
<p><strong>6、提供安全机制</strong></p>
<p>　　解决REST安全调用问题，可以做得很复杂，也可以做得特简单，可按照以下过程提供REST安全机制：</p>
<p>　　(1). 当用户登录成功后，在服务端生成一个token，并将其放入内存中（可放入JVM或Redis中），同时将该token返回到客户端；</p>
<p>　　(2). 在客户端中将返回的token写入cookie中，并且每次请求时都将token随请求头一起发送到服务端；</p>
<p>　　(3). 提供一个AOP切面，用于拦截所有的Controller方法，在切面中判断token的有效性；</p>
<p>　　(4). 当登出时，只需清理掉cookie中的token即可，服务端token可设置过期时间，使其自行移除。</p>
<p>　　首先，我们需要定义一个用于管理token的接口，包括创建token与检查token有效性的功能。代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;**        </span><br><span class="line"> * Title: REST 鉴权   </span><br><span class="line"> * Description: 登录用户的身份鉴权</span><br><span class="line"> * @author rico       </span><br><span class="line"> * @created 2017年7月4日 下午4:41:43    </span><br><span class="line"> *&#x2F;      </span><br><span class="line">public interface TokenManager &#123;</span><br><span class="line"></span><br><span class="line">    String createToken(String username);  </span><br><span class="line"></span><br><span class="line">    boolean checkToken(String token); </span><br><span class="line"></span><br><span class="line">    void deleteToken(String token);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后，我们可提供一个简单的TokenManager实现类，将token存储到JVM内存中。代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;**        </span><br><span class="line"> * Title: TokenManager的默认实现    </span><br><span class="line"> * Description: 管理 Token</span><br><span class="line"> * @author rico       </span><br><span class="line"> * @created 2017年7月4日 下午4:41:32    </span><br><span class="line"> *&#x2F;      </span><br><span class="line">public class DefaultTokenManager implements TokenManager &#123;</span><br><span class="line"></span><br><span class="line">    &#x2F;** 将token存储到JVM内存(ConcurrentHashMap)中   (@author: rico) *&#x2F;      </span><br><span class="line">    private static Map&lt;String, String&gt; tokenMap &#x3D; new ConcurrentHashMap&lt;String, String&gt;();</span><br><span class="line"></span><br><span class="line">    &#x2F;** </span><br><span class="line">     * @description 利用UUID创建Token(用户登录时，创建Token)</span><br><span class="line">     * @author rico       </span><br><span class="line">     * @created 2017年7月4日 下午4:46:46      </span><br><span class="line">     * @param username</span><br><span class="line">     * @return     </span><br><span class="line">     * @see cn.edu.tju.rico.authorization.TokenManager#createToken(java.lang.String)     </span><br><span class="line">     *&#x2F;  </span><br><span class="line">    public String createToken(String username) &#123;</span><br><span class="line">        String token &#x3D; CodecUtil.createUUID();</span><br><span class="line">        tokenMap.put(token, username);</span><br><span class="line">        return token;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#x2F;** </span><br><span class="line">     * @description Token验证(用户登录验证)</span><br><span class="line">     * @author rico       </span><br><span class="line">     * @created 2017年7月4日 下午4:46:50      </span><br><span class="line">     * @param token</span><br><span class="line">     * @return     </span><br><span class="line">     * @see cn.edu.tju.rico.authorization.TokenManager#checkToken(java.lang.String)     </span><br><span class="line">     *&#x2F;  </span><br><span class="line">    public boolean checkToken(String token) &#123;</span><br><span class="line">        return !StringUtil.isEmpty(token) &amp;&amp; tokenMap.containsKey(token);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#x2F;** </span><br><span class="line">     * @description Token删除(用户登出时，删除Token)</span><br><span class="line">     * @author rico       </span><br><span class="line">     * @created 2017年7月4日 下午4:46:54      </span><br><span class="line">     * @param token     </span><br><span class="line">     * @see cn.edu.tju.rico.authorization.TokenManager#deleteToken(java.lang.String)     </span><br><span class="line">     *&#x2F;  </span><br><span class="line">    @Override</span><br><span class="line">    public void deleteToken(String token) &#123;</span><br><span class="line">        &#x2F;&#x2F; TODO Auto-generated method stub</span><br><span class="line">        tokenMap.remove(token);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>需要注意的是，如果需要做到分布式集群，建议基于Redis提供一个实现类，将token存储到Redis中，并利用Redis与生俱来的特性，做到token的分布式一致性。 </p>
<p>然后，我们可以基于Spring AOP写一个切面类，用于拦截Controller类的方法，并从请求头中获取token，最后对token有效性进行判断。代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;**</span><br><span class="line"> * Title:安全检查切面(是否登录检查) </span><br><span class="line"> * Description: 通过验证Token维持登录状态</span><br><span class="line"> * </span><br><span class="line"> * @author rico</span><br><span class="line"> * @created 2017年7月4日 下午4:32:34</span><br><span class="line"> *&#x2F;</span><br><span class="line">@Component</span><br><span class="line">@Aspect</span><br><span class="line">public class SecurityAspect &#123;</span><br><span class="line"></span><br><span class="line">    &#x2F;** Log4j日志处理(@author: rico) *&#x2F;</span><br><span class="line">    private static final Logger log &#x3D; Logger.getLogger(SecurityAspect.class);</span><br><span class="line"></span><br><span class="line">    private TokenManager tokenManager;</span><br><span class="line"></span><br><span class="line">    @Resource(name &#x3D; &quot;tokenManager&quot;)</span><br><span class="line">    public void setTokenManager(TokenManager tokenManager) &#123;</span><br><span class="line">        this.tokenManager &#x3D; tokenManager;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Around(&quot;@annotation(org.springframework.web.bind.annotation.RequestMapping)&quot;)</span><br><span class="line">    public Object execute(ProceedingJoinPoint pjp) throws Throwable &#123;</span><br><span class="line">        &#x2F;&#x2F; 从切点上获取目标方法</span><br><span class="line">        MethodSignature methodSignature &#x3D; (MethodSignature) pjp.getSignature();</span><br><span class="line">        log.debug(&quot;methodSignature : &quot; + methodSignature);</span><br><span class="line">        Method method &#x3D; methodSignature.getMethod();</span><br><span class="line">        log.debug(&quot;Method : &quot; + method.getName() + &quot; : &quot;</span><br><span class="line">                + method.isAnnotationPresent(IgnoreSecurity.class));</span><br><span class="line">        &#x2F;&#x2F; 若目标方法忽略了安全性检查,则直接调用目标方法</span><br><span class="line">        if (method.isAnnotationPresent(IgnoreSecurity.class)) &#123;</span><br><span class="line">            return pjp.proceed();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        &#x2F;&#x2F; 从 request header 中获取当前 token</span><br><span class="line">        String token &#x3D; WebContextUtil.getRequest().getHeader(</span><br><span class="line">                Constants.DEFAULT_TOKEN_NAME);</span><br><span class="line">        &#x2F;&#x2F; 检查 token 有效性</span><br><span class="line">        if (!tokenManager.checkToken(token)) &#123;</span><br><span class="line">            String message &#x3D; String.format(&quot;token [%s] is invalid&quot;, token);</span><br><span class="line">            log.debug(&quot;message : &quot; + message);</span><br><span class="line">            throw new TokenException(message);</span><br><span class="line">        &#125;</span><br><span class="line">        &#x2F;&#x2F; 调用目标方法</span><br><span class="line">        return pjp.proceed();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>若要使SecurityAspect生效，则需要在SpringMVC配置文件中添加如下Spring 配置：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- 启用注解扫描，并定义组件查找规则 ，mvc层只负责扫描@Controller、@ControllerAdvice --&gt;</span><br><span class="line">    &lt;!-- base-package 如果多个，用“,”分隔 --&gt;</span><br><span class="line">    &lt;context:component-scan base-package&#x3D;&quot;cn.edu.tju.rico&quot;</span><br><span class="line">        use-default-filters&#x3D;&quot;false&quot;&gt;</span><br><span class="line">        &lt;!-- 扫描 @Controller --&gt;</span><br><span class="line">        &lt;context:include-filter type&#x3D;&quot;annotation&quot;</span><br><span class="line">            expression&#x3D;&quot;org.springframework.stereotype.Controller&quot; &#x2F;&gt;</span><br><span class="line">        &lt;!-- 控制器增强，使一个Contoller成为全局的异常处理类，类中用@ExceptionHandler方法注解的方法可以处理所有Controller发生的异常 --&gt;</span><br><span class="line">        &lt;context:include-filter type&#x3D;&quot;annotation&quot;</span><br><span class="line">            expression&#x3D;&quot;org.springframework.web.bind.annotation.ControllerAdvice&quot; &#x2F;&gt;</span><br><span class="line">    &lt;&#x2F;context:component-scan&gt;</span><br><span class="line"></span><br><span class="line">    &lt;!-- 支持Controller的AOP代理 --&gt;</span><br><span class="line">    &lt;aop:aspectj-autoproxy &#x2F;&gt;</span><br></pre></td></tr></table></figure>

<p>最后，别忘了在web.xml中添加允许的X-Token响应头，配置如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;init-param&gt;  </span><br><span class="line">    &lt;param-name&gt;allowHeaders&lt;&#x2F;param-name&gt;  </span><br><span class="line">    &lt;param-value&gt;Content-Type,X-Token&lt;&#x2F;param-value&gt;  </span><br><span class="line">&lt;&#x2F;init-param&gt;  </span><br></pre></td></tr></table></figure>

<h2 id="四-关于Demo部署的若干建议"><a href="#四-关于Demo部署的若干建议" class="headerlink" title="四. 关于Demo部署的若干建议"></a>四. 关于Demo部署的若干建议</h2><p>　　本项目是一个使用Maven进行构建的项目，关于Maven的了解、使用推荐大家看孤傲苍狼的<a target="_blank" rel="noopener" href="http://www.cnblogs.com/xdp-gacl/tag/Maven%E5%AD%A6%E4%B9%A0%E6%80%BB%E7%BB%93/">《Maven学习总结》</a>一系列博客；</p>
<p>　　关于REST服务的调试推荐大家使用Postman这款工具，请大家自行下载与安装，具体见<a target="_blank" rel="noopener" href="http://www.cnblogs.com/hubgit/p/6589701.html">《postman的安装与使用（模拟请求）》</a>；</p>
<hr>
<h2 id="五-总结"><a href="#五-总结" class="headerlink" title="五. 总结"></a>五. 总结</h2><p>　　本文从经典的MVC模式开始，对MVC模式是什么以及该模式存在的不足进行了简述。然后引出了如何对MVC模式的改良，让其转变为前后端分离架构，以及解释了为何要进行前后端分离。最后通过REST服务将前后端进行解耦，并提供了一款基于Java的REST框架的主要实现过程，尤其是需要注意的核心技术问题及其解决方案。希望本文对正在探索前后端分离的读者们有所帮助，期待与大家共同探讨。 
　　</p>
<hr>
<h2 id="六-更多"><a href="#六-更多" class="headerlink" title="六. 更多"></a>六. 更多</h2><p>本项目的全部完整源码可以在我的GitHub上找到，项目名为RestSpringMVCDemo，项目地址为：<a target="_blank" rel="noopener" href="https://github.com/githubofrico/RestSpringMVCDemo%E3%80%82">https://github.com/githubofrico/RestSpringMVCDemo。</a></p>
<p>更多关于REST的介绍，请移步我的博文<a target="_blank" rel="noopener" href="http://blog.csdn.net/justloveyou_/article/details/73612999">《理解RESTful架构》</a>。</p>
<p>更多关于 Java Web 方面的内容，请关注我的专栏 <a target="_blank" rel="noopener" href="http://static.zybuluo.com/Rico123/et4q5o2ok4ryi6dniwifvcx0/MVC.jpg">《Java Web 成神之路》</a>。本专栏全面记录了Java Web开发相关知识，不但包括对http, servlet,session等基础知识的讲解，还包括对流行框架(SSM,SpringMVC等)、中间件(Redis等)等进阶知识的深入分析。笔者将持续跟进最新Web技术，期望对大家能够起到抛砖引玉的效果。</p>
<h2 id="本文转载自：https-www-cnblogs-com-softidea-p-8144890-html"><a href="#本文转载自：https-www-cnblogs-com-softidea-p-8144890-html" class="headerlink" title="本文转载自：https://www.cnblogs.com/softidea/p/8144890.html"></a>本文转载自：<a target="_blank" rel="noopener" href="https://www.cnblogs.com/softidea/p/8144890.html">https://www.cnblogs.com/softidea/p/8144890.html</a></h2>
      
    </div>
    
    
    
    
    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Joy Wang
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://joy_24.gitee.io/2020/11/25/rest1/" title="REST风格框架实战（从MVC到前后端分离）">https://joy_24.gitee.io/2020/11/25/rest1/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/myblogs/tags/REST-%E5%89%8D%E7%AB%AF%EF%BC%8C%E5%90%8E%E7%AB%AF/" rel="tag"># REST,前端，后端</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/myblogs/2020/11/25/ideaUseTutorial/" rel="next" title="IDEA使用教程">
                <i class="fa fa-chevron-left"></i> IDEA使用教程
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/myblogs/2020/11/26/idea-hotKey-1/" rel="prev" title="idea 这样配置，快到飞起">
                idea 这样配置，快到飞起 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/myblogs/uploads/avatar.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                #<a href="/myblogs/archives%7C%7C%20archive">
                <a href="/myblogs/archives">
              
                  <span class="site-state-item-count">34</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/myblogs/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/myblogs/tags/index.html">
                  <span class="site-state-item-count">20</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/myblogs/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/joyWJ" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="wangjianjoy@126.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%80-MVC-%E6%A6%82%E8%BF%B0"><span class="nav-number">1.</span> <span class="nav-text">一. MVC 概述</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#MVC%E6%A8%A1%E5%BC%8F%E6%97%A9%E5%9C%A8%E4%B8%8A%E4%B8%AA%E4%B8%96%E7%BA%AA70%E5%B9%B4%E4%BB%A3%E5%B0%B1%E8%AF%9E%E7%94%9F%E4%BA%86%EF%BC%8C%E7%9B%B4%E5%88%B0%E4%BB%8A%E5%A4%A9%E5%AE%83%E4%BE%9D%E7%84%B6%E5%AD%98%E5%9C%A8%EF%BC%8C%E5%8F%AF%E8%A7%81%E7%94%9F%E5%91%BD%E5%8A%9B%E7%9B%B8%E5%BD%93%E4%B9%8B%E5%BC%BA%E3%80%82MVC%E6%A8%A1%E5%BC%8F%E6%9C%80%E6%97%A9%E5%BA%94%E7%94%A8%E4%BA%8ESmalltalk%E8%AF%AD%E8%A8%80%E4%B8%AD%EF%BC%8C%E6%9C%80%E5%90%8E%E5%9C%A8%E5%85%B6%E5%AE%83%E8%AE%B8%E5%A4%9A%E5%BC%80%E5%8F%91%E8%AF%AD%E8%A8%80%E4%B8%AD%E9%83%BD%E5%BE%97%E5%88%B0%E4%BA%86%E5%BE%88%E5%A5%BD%E7%9A%84%E5%BA%94%E7%94%A8%E3%80%82%E9%9A%8F%E7%9D%80%E5%8C%85%E6%8B%ACStruts%E3%80%81Spring-MVC%E5%9C%A8%E5%86%85%E7%9A%84MVC%E6%A1%86%E6%9E%B6%E7%9A%84%E5%87%BA%E7%8E%B0%EF%BC%8CMVC%E6%A8%A1%E5%BC%8F%E7%9C%9F%E6%AD%A3%E8%90%BD%E5%9C%B0%EF%BC%8C%E5%B9%B6%E4%BD%BF%E5%BE%97%E5%BC%80%E5%8F%91%E6%9B%B4%E5%8A%A0%E9%AB%98%E6%95%88%E3%80%81%E4%BB%A3%E7%A0%81%E8%80%A6%E5%90%88%E5%BA%A6%E5%B0%BD%E9%87%8F%E5%87%8F%E5%B0%8F%E3%80%81%E5%BA%94%E7%94%A8%E7%A8%8B%E5%BA%8F%E5%90%84%E9%83%A8%E5%88%86%E7%9A%84%E8%81%8C%E8%B4%A3%E6%9B%B4%E5%8A%A0%E6%B8%85%E6%99%B0%E3%80%82"><span class="nav-number">1.0.0.1.</span> <span class="nav-text">　　MVC模式早在上个世纪70年代就诞生了，直到今天它依然存在，可见生命力相当之强。MVC模式最早应用于Smalltalk语言中，最后在其它许多开发语言中都得到了很好的应用。随着包括Struts、Spring MVC在内的MVC框架的出现，MVC模式真正落地，并使得开发更加高效、代码耦合度尽量减小、应用程序各部分的职责更加清晰。</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8C-%E8%AE%A4%E8%AF%86-REST"><span class="nav-number">2.</span> <span class="nav-text">二. 认识 REST</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%89-%E5%AE%9E%E7%8E%B0REST%E6%A1%86%E6%9E%B6"><span class="nav-number">3.</span> <span class="nav-text">三. 实现REST框架</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9B%9B-%E5%85%B3%E4%BA%8EDemo%E9%83%A8%E7%BD%B2%E7%9A%84%E8%8B%A5%E5%B9%B2%E5%BB%BA%E8%AE%AE"><span class="nav-number">4.</span> <span class="nav-text">四. 关于Demo部署的若干建议</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%94-%E6%80%BB%E7%BB%93"><span class="nav-number">5.</span> <span class="nav-text">五. 总结</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%AD-%E6%9B%B4%E5%A4%9A"><span class="nav-number">6.</span> <span class="nav-text">六. 更多</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9C%AC%E6%96%87%E8%BD%AC%E8%BD%BD%E8%87%AA%EF%BC%9Ahttps-www-cnblogs-com-softidea-p-8144890-html"><span class="nav-number">7.</span> <span class="nav-text">本文转载自：https:&#x2F;&#x2F;www.cnblogs.com&#x2F;softidea&#x2F;p&#x2F;8144890.html</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Joy Wang</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/myblogs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/myblogs/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/myblogs/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/myblogs/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/myblogs/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/myblogs/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/myblogs/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/myblogs/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
